<template>
  <div class="mod-wrap">
    <xkl-form :data-form="dataForm" :data-form-config="dataFormConfig">
      <template slot="searchAndRefresh">
        <el-button type="warning" icon="el-icon-search" @click="getSearchDataList()">查询</el-button>
        <el-button type="primary" icon="el-icon-refresh" @click="resetForm()">重置</el-button>
      </template>
      <template slot="functionBtns">
        <el-button size="mini" type="primary" icon="el-icon-circle-plus-outline" @click="addOrUpdateHandle()">新增</el-button>
        <el-button size="mini" type="danger" :disabled="!dataListSelections.length" @click="deleteHandle()">
          <icon-svg name="批量删除" style="vertical-align: middle"></icon-svg>
          批量删除</el-button>
      </template>
    </xkl-form>
    <xkl-table
      index="true"
      selection="true"
      :table-column="tableColumn"
      :data-list="dataList"
      :dataListLoading="dataListLoading"
      @selection-change="selectionChangeHandle">
      <!--当table配置参数中开启了slot即可使用以下模板：-->
      <!--<template slot="test1" slot-scope="{ row }">{{row.test1}}</template>-->
      <template slot="operation" slot-scope="{ row }">
        <el-button type="text" size="small" icon="el-icon-info" @click="showDetails(row.id)">详情</el-button>
        <el-button type="text" size="small" icon="el-icon-edit" @click="addOrUpdateHandle(row.id)">修改</el-button>
        <el-button type="text" size="small" icon="el-icon-delete" @click="deleteHandle(row.id)">删除</el-button>
      </template>
    </xkl-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>
    <details-show v-if="detailsVisible" ref="detailsShow"></details-show>
  </div>
</template>

<script>
  import AddOrUpdate from './add-or-update'
  import DetailsShow from './details'
  export default {
    data () {
      return {
        pageIndex: 1,
        pageSize: 10,
        totalCount: 0,
        dataForm: {
          test1: '',
          test2: ''
        },
        dataFormConfig: {
          /** baseConfig 用于配置表单基本结构，
           ...其余参数满足以下下规则：
           字段名称: {
             label: 字段label名称,
             placeholder: 若不填则默认为label名称,
             type: 输入框类型,可选值（'select', 'date-时间框类型 如：date-year'）
             config: 输入框类型为下拉框时配置生效，其中参数为{selectType: 字典类型, keyType: value取值, labelType: label取值, link: 下拉框接口地址}
             additionalData: 下拉框传送额外参数
             maxLength: 可输入最大长度
             isRequired: 是否必填
             disabled: 是否禁用
             span: 自定义span大小，默认为baseConfig中的span值
           }
           列表排列顺序为字段排列顺序 */
          baseConfig: {span: 8, labelWidth: 100},
          test1: {label: '测试1'},
          test2: {label: '测试2', maxLength: 8}
        },
        tableColumn: [],
        dataList: [],
        dataListSelections: [],
        addOrUpdateVisible: false,
        detailsVisible: false,
        dataListLoading: false
      }
    },
    components: {
      AddOrUpdate,
      DetailsShow
    },
    activated () {
      this.resetForm()
    },
    created () {
      this.resetForm()
    },
    methods: {
      init () {
        this.tableColumn = [
          // 用于定义列表字段参数分别对应为['prop', 'label', 'min-width', 'slot', 'custom']
          // slot 开启时min-width 变为 width
          // ['OPERATION', 200] 设置操作列宽
          ['test1', '测试1', 100, true],
          ['test2', '测试2', 120],
          ['test3', '测试3', 200],
          ['test4', '测试4'],
          ['test5', '测试5'],
          ['OPERATION', 200]
        ]
        this.getDataList()
      },
      getSearchDataList () {
        this.pageIndex = 1
        this.getDataList()
      },
      // 获取数据列表
      getDataList () {
        this.dataList = []
        this.dataListLoading = true
        let handleData = this.handleDataForm()
        this.$http({
          url: this.$http.adornUrl('/dict/list'),
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            ...handleData
          }, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.testList
            this.totalCount = data.pagination.total
            this.changeData(data.testList)
          } else {
            this.dataList = []
            this.totalCount = 0
          }
          this.dataListLoading = false
        })
      },
      handleDataForm () {
        let handleData = JSON.parse(JSON.stringify(this.dataForm))
        // 处理要传递的数据
        Object.keys(handleData).forEach(res => {
          if (!handleData[res]) handleData[res] = undefined
        })
        // 返回已处理的数据
        return handleData
      },
      changeData () {
        // 自定义数据展示形式
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle (val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle (id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      // 详情
      showDetails (id) {
        this.detailsVisible = true
        this.$nextTick(() => {
          this.$refs.detailsShow.init(id)
        })
      },
      // 删除
      deleteHandle (id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.id
        })
        this.$confirm(`确定删除${id ? '这条' : '选中'}数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/test/test/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({message: '操作成功', type: 'success', duration: 1500, onClose: () => this.getDataList()})
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      },
      resetForm () {
        this.$resetData(this.dataForm)
        this.pageIndex = 1
        this.pageSize = 10
        this.init()
      }
    }
  }
</script>
